<template>
  <div class="meading-form-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="工单编号">
          <el-input v-model="searchParams.workOrderCode" placeholder="请输入工单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="工单名称">
          <el-input v-model="searchParams.workOrderName" placeholder="请输入工单名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="来源类型">
          <el-select v-model="searchParams.workOrderSource" placeholder="请选择来源类型" clearable style="width: 120px;">
            <el-option v-for="item in sourceTypeOptions" :key="item.key" :label="item.label" :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单类型">
          <el-select v-model="searchParams.workOrderType" placeholder="请选择工单类型" clearable style="width: 120px;">
            <el-option v-for="item in orderTypeOptions" :key="item.key" :label="item.label" :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input v-model="searchParams.productNumber" placeholder="请输入产品编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="searchParams.productName" placeholder="请输入产品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="searchParams.clientCode" placeholder="请输入客户编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="需求日期">
          <el-date-picker v-model="searchParams.needsDate" type="date" placeholder="请选择需求日期" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>新增
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          <el-icon>
            <Delete />
          </el-icon>批量删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table ref="orderTable" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange"
        v-loading="loading" highlight-current-row>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="workOrderCode" label="工单编号" width="150"></el-table-column>
        <el-table-column prop="workOrderName" label="工单名称" width="150"></el-table-column>
        <el-table-column prop="workOrderType" label="工单类型" width="100">
          <template #default="scope">
            {{ getOrderTypeText(scope.row.workOrderType) }}
          </template>
        </el-table-column>
        <el-table-column prop="workOrderSource" label="来源类型" width="100">
          <template #default="scope">
            {{ getSourceTypeText(scope.row.workOrderSource) }}
          </template>
        </el-table-column>
        <el-table-column prop="productNumber" label="产品编号" width="150"></el-table-column>
        <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
        <el-table-column prop="specification" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="unit" label="单位" width="80"></el-table-column>
        <el-table-column prop="planQuantity" label="工单数量" width="100"></el-table-column>
        <el-table-column prop="finishedQuantity" label="已生产数量" width="120"></el-table-column>
        <el-table-column prop="clientCode" label="客户编号" width="120"></el-table-column>
        <el-table-column prop="clientName" label="客户名称" width="200"></el-table-column>
        <el-table-column prop="needsDate" label="需求日期" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.needsDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ total }} 条</span>
        <el-select v-model="pageSize" placeholder="条/页" style="width: 100px">
          <el-option :value="10" label="10条/页"></el-option>
          <el-option :value="20" label="20条/页"></el-option>
          <el-option :value="50" label="50条/页"></el-option>
          <el-option :value="100" label="100条/页"></el-option>
        </el-select>
        <el-pagination layout="prev, pager, next, jumper" :total="total" :page-size="pageSize"
          :current-page="currentPage" @current-change="handleCurrentChange" @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑生产工单' : '添加生产工单'" width="1200px"
      :close-on-click-modal="false" :show-close="true" @close="resetForm" center>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right"
        class="order-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编号" prop="workOrderCode" required>
              <el-input v-model="formData.workOrderCode" placeholder="请输入工单编号" style="width: 80%">
                <template #append>
                  <el-switch v-model="autoGenerateCode" active-text="自动生成" inactive-text=""
                    @change="handleAutoGenerateChange"></el-switch>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workOrderName" required>
              <el-input v-model="formData.workOrderName" placeholder="请输入工单名称" style="width: 80%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源类型" prop="workOrderSource" required>
              <el-radio-group v-model="formData.workOrderSource">
                <el-radio label="客户订单">客户订单</el-radio>
                <el-radio label="库存备货">库存备货</el-radio>
                <el-radio label="特别生产">特别生产</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型" prop="workOrderType" required>
              <el-select v-model="formData.workOrderType" placeholder="请选择工单类型" style="width: 80%">
                <el-option v-for="item in orderTypeOptions" :key="item.key" :label="item.label" :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productNumber" required>
              <div class="search-input-container">
                <el-input v-model="formData.productNumber" placeholder="请选择产品" readonly style="width: 80%"></el-input>
                <el-button @click="openProductDialog" class="search-button">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="产品名称" readonly style="width: 80%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="formData.specification" placeholder="规格型号" readonly style="width: 80%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formData.unit" placeholder="单位" readonly style="width: 80%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编号" prop="clientCode">
              <div class="search-input-container">
                <el-input v-model="formData.clientCode" placeholder="请输入客户编号" readonly style="width: 80%"></el-input>
                <el-button @click="openCustomerDialog" class="search-button">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="formData.clientName" placeholder="请输入客户名称" readonly style="width: 80%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单数量" prop="planQuantity" required>
              <el-input-number v-model="formData.planQuantity" :min="1" controls-position="right"
                style="width: 80%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求日期" prop="needsDate" required>
              <el-date-picker v-model="formData.needsDate" type="date" placeholder="请选择需求日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 80%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入内容" style="width: 80%">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品选择对话框 -->
    <el-dialog v-model="productDialogVisible" title="选择产品" width="1000px" :close-on-click-modal="false"
      class="product-dialog custom-dialog" center>
      <div class="product-dialog-container">
        <!-- 左侧产品类型树 -->
        <div class="product-type-tree">
          <div class="tree-header">
            <h3>产品类型</h3>
            <el-input v-model="treeFilterText" placeholder="搜索类型" clearable prefix-icon="Search" size="small" />
          </div>
          <div class="tree-content">
            <el-tree ref="productTypeTreeRef" :data="productTypeTree"
              :props="{ label: (data) => data.name || data.classifyName || '未命名', children: 'children' }" node-key="id"
              highlight-current :filter-node-method="filterNode" @node-click="handleNodeClick"
              v-loading="treeLoading" />
          </div>
        </div>

        <!-- 右侧产品列表 -->
        <div class="product-list-container">
          <div class="product-search">
            <el-form :inline="true">
              <el-form-item label="产品编码">
                <el-input v-model="productSearchForm.materialCode" placeholder="请输入产品编码" clearable></el-input>
              </el-form-item>
              <el-form-item label="产品名称">
                <el-input v-model="productSearchForm.materialName" placeholder="请输入产品名称" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchProducts">搜索</el-button>
                <el-button @click="resetProductSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table ref="selectProductTableRef" :data="availableProducts" style="width: 100%"
            @row-click="handleProductRowClick" highlight-current-row row-key="materialId" border stripe
            v-loading="productSearchLoading" element-loading-text="搜索中..." max-height="350">
            <el-table-column prop="materialCode" label="产品编码" width="150" />
            <el-table-column prop="materialName" label="产品名称" width="180" />
            <el-table-column prop="specification" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="category" label="产品类别" />
          </el-table>

          <div class="product-pagination">
            <el-pagination v-model:current-page="productSearchPagination.currentPage"
              v-model:page-size="productSearchPagination.pageSize" :page-sizes="[5, 10, 20]"
              layout="total, sizes, prev, pager, next" :total="productSearchPagination.total"
              @size-change="handleProductSearchSizeChange" @current-change="handleProductSearchCurrentChange" small />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectProduct">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 客户选择对话框 -->
    <el-dialog v-model="customerDialogVisible" title="客户选择" width="1000px" :close-on-click-modal="false"
      class="customer-dialog custom-dialog" center>
      <div class="customer-search">
        <el-form :inline="true">
          <el-form-item label="客户编号">
            <el-input v-model="customerSearchForm.custCode" placeholder="请输入客户编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="customerSearchForm.custName" placeholder="请输入客户名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="customerSearchForm.custPhone" placeholder="请输入联系电话" clearable></el-input>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-select v-model="customerSearchForm.isEnable" placeholder="请选择" clearable>
              <el-option :value="1" label="启用"></el-option>
              <el-option :value="0" label="禁用"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchCustomers">搜索</el-button>
            <el-button @click="resetCustomerSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table ref="customerTableRef" :data="customerList" style="width: 100%" @row-click="handleCustomerRowClick"
        highlight-current-row row-key="custId" border stripe v-loading="customerLoading" element-loading-text="搜索中..."
        max-height="350">
        <el-table-column width="70">
          <template #default="scope">
            <el-radio v-model="selectedCustomerId" :label="scope.row.custId || scope.row.id"
              @change="() => handleCustomerRadioChange(scope.row)">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="custCode" label="客户编号" width="120" />
        <el-table-column prop="custName" label="客户名称" width="200" />
        <el-table-column prop="custPhone" label="联系电话" width="120" />
        <el-table-column prop="custType" label="客户类型" width="120" />
        <el-table-column prop="conPerson" label="联系人" width="100" />
        <el-table-column prop="custPhone" label="联系人电话" width="120" />
      </el-table>

      <div class="customer-pagination">
        <el-pagination v-model:current-page="customerPagination.currentPage"
          v-model:page-size="customerPagination.pageSize" :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next" :total="customerPagination.total"
          @size-change="handleCustomerSizeChange" @current-change="handleCustomerCurrentChange" small />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="customerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectCustomer">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 数据加载状态
const loading = ref(false)

// 表格选中项
const selectedIds = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索参数
const searchParams = reactive({
  workOrderCode: '',
  workOrderName: '',
  workOrderSource: '',
  workOrderType: '',
  productNumber: '',
  productName: '',
  clientCode: '',
  needsDate: ''
})

// 表格数据
const tableData = ref([])

// 来源类型选项
const sourceTypeOptions = [
  { key: '1', label: '客户订单' },
  { key: '2', label: '库存备货' },
  { key: '3', label: '特别生产' }
]

// 工单类型选项
const orderTypeOptions = [
  { key: '1', label: '顺序生产' },
  { key: '2', label: '常规生产' },
  { key: '3', label: '加急生产' },
  { key: '4', label: '返修制作' },
  { key: '5', label: '维修备件' },
  { key: '6', label: '内部制作' },
  { key: '7', label: '外部生产' },
  { key: '8', label: '半成品' }
]

// 对话框显示控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const autoGenerateCode = ref(true)

// 表单引用
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  workOrderCode: '',
  workOrderName: '',
  workOrderSource: '客户订单',
  workOrderType: '顺序生产',
  productNumber: '',
  productName: '',
  specification: '',
  unit: '',
  planQuantity: 1,
  finishedQuantity: 0,
  clientCode: '',
  clientName: '',
  needsDate: '',
  status: 0,
  remark: ''
})

// 表单验证规则
const formRules = {
  workOrderName: [{ required: true, message: '请输入工单名称', trigger: 'blur' }],
  workOrderSource: [{ required: true, message: '请选择来源类型', trigger: 'change' }],
  workOrderType: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
  productNumber: [{ required: true, message: '请选择产品', trigger: 'blur' }],
  planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
  needsDate: [{ required: true, message: '请选择需求日期', trigger: 'change' }]
}

// 产品选择对话框
const productDialogVisible = ref(false)
const productSearchKeyword = ref('')
const productList = ref([])
const selectedProduct = ref(null)
const productLoading = ref(false)
const productCurrentPage = ref(1)
const productPageSize = ref(10)
const productTotal = ref(0)

// 产品类型树相关
const productTypeTree = ref([])
const productTypeTreeRef = ref(null)
const treeLoading = ref(false)
const treeFilterText = ref('')
const currentProductTypeId = ref(null)

// 监听树形过滤文本变化
watch(treeFilterText, (val) => {
  productTypeTreeRef.value?.filter(val)
})

// 树形节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return (data.name || data.classifyName || '').includes(value)
}

// 树形节点点击事件
const handleNodeClick = (data) => {
  console.log('选中的产品类型:', data)
  currentProductTypeId.value = data.id
  productSearchForm.materialTypeId = data.id
  productSearchForm.flatsMaterial = data.name || data.classifyName // 使用树节点的名称
  searchProducts()
}

// 获取产品类型树数据
const fetchProductTypeTree = async () => {
  try {
    treeLoading.value = true
    const response = await axios.get('/api/Allot/GetMaterialTypeList')

    if (response.data && response.data.data && Array.isArray(response.data.data)) {
      productTypeTree.value = response.data.data
    } else if (response.data && Array.isArray(response.data)) {
      productTypeTree.value = response.data
    } else {
      productTypeTree.value = []
      console.error('获取产品类型树数据格式不正确:', response.data)
    }
  } catch (error) {
    console.error('获取产品类型树数据出错:', error)
    ElMessage.error('获取产品类型树数据出错，请稍后重试')
    productTypeTree.value = []
  } finally {
    treeLoading.value = false
  }
}

// 产品搜索相关
const productSearchForm = reactive({
  materialCode: '',
  materialName: '',
  materialTypeId: null,
  flatsMaterial: ''
})

const availableProducts = ref([])
const selectProductTableRef = ref(null)
const productSearchLoading = ref(false)

const productSearchPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 产品搜索分页处理
const handleProductSearchSizeChange = (size) => {
  productSearchPagination.pageSize = size
  searchProducts()
}

const handleProductSearchCurrentChange = (current) => {
  productSearchPagination.currentPage = current
  searchProducts()
}

// 产品行点击事件
const handleProductRowClick = (row) => {
  selectedProduct.value = row
  selectProductTableRef.value?.setCurrentRow(row)
}

// 产品搜索
const searchProducts = async () => {
  try {
    productSearchLoading.value = true

    // 构建请求参数
    const params = {
      materialCode: productSearchForm.materialCode || '',
      materialName: productSearchForm.materialName || '',
      materialTypeId: productSearchForm.materialTypeId || null,
      flatsMaterial: productSearchForm.flatsMaterial || '',
      pageIndex: productSearchPagination.currentPage,
      pageSize: productSearchPagination.pageSize
    }

    // 调用API搜索产品
    const response = await axios.post('/api/Allot/GetMaterial', params)

    if (response.data && response.data.rows) {
      availableProducts.value = response.data.rows
      productSearchPagination.total = response.data.total || 0
    } else if (response.data && response.data.data) {
      availableProducts.value = response.data.data.rows || []
      productSearchPagination.total = response.data.data.total || 0
    } else {
      availableProducts.value = []
      productSearchPagination.total = 0
    }

    // 清空选中项
    if (selectProductTableRef.value) {
      selectProductTableRef.value.clearSelection()
    }
    selectedProduct.value = null
  } catch (error) {
    console.error('搜索产品出错:', error)
    ElMessage.error('搜索产品出错，请稍后重试')
    availableProducts.value = []
    productSearchPagination.total = 0
  } finally {
    productSearchLoading.value = false
  }
}

// 重置产品搜索条件
const resetProductSearch = () => {
  productSearchForm.materialCode = ''
  productSearchForm.materialName = ''
  productSearchForm.materialTypeId = null
  productSearchForm.flatsMaterial = ''
  currentProductTypeId.value = null
  productSearchPagination.currentPage = 1

  // 清除树形选中状态
  if (productTypeTreeRef.value) {
    productTypeTreeRef.value.setCurrentKey(null)
  }

  searchProducts()
}

// 客户选择对话框
const customerDialogVisible = ref(false)
const customerList = ref([])
const selectedCustomer = ref(null)
const selectedCustomerId = ref('') // 用于单选按钮的绑定值
const customerLoading = ref(false)
const customerTableRef = ref(null)

// 客户搜索表单
const customerSearchForm = reactive({
  custCode: '',
  custName: '',
  custPhone: '',
  isEnable: 1
})

// 客户分页
const customerPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 客户分页处理
const handleCustomerSizeChange = (size) => {
  customerPagination.pageSize = size
  searchCustomers()
}

const handleCustomerCurrentChange = (current) => {
  customerPagination.currentPage = current
  searchCustomers()
}

// 打开客户选择对话框
const openCustomerDialog = () => {
  resetCustomerSearch()
  customerDialogVisible.value = true
  searchCustomers()
}

// 搜索客户
const searchCustomers = async () => {
  try {
    customerLoading.value = true

    // 构建请求参数
    const params = {
      pageIndex: customerPagination.currentPage,
      pageSize: customerPagination.pageSize,
      custCode: customerSearchForm.custCode || '',
      custName: customerSearchForm.custName || '',
      custPhone: customerSearchForm.custPhone || '',
      isEnable: customerSearchForm.isEnable
    }

    // 调用API
    const response = await axios.post('/api/OutProductCheck/GetCustomerList', params)

    // 处理响应数据
    if (response.data && response.data.rows) {
      customerList.value = response.data.rows
      customerPagination.total = response.data.total || 0
    } else if (response.data && response.data.data) {
      customerList.value = response.data.data.rows || []
      customerPagination.total = response.data.data.total || 0
    } else {
      customerList.value = []
      customerPagination.total = 0
    }

    // 清空选中项
    if (customerTableRef.value) {
      customerTableRef.value.clearSelection()
    }
    selectedCustomer.value = null
  } catch (error) {
    console.error('搜索客户出错:', error)
    ElMessage.error('搜索客户出错，请稍后重试')
    customerList.value = []
    customerPagination.total = 0
  } finally {
    customerLoading.value = false
  }
}

// 重置客户搜索条件
const resetCustomerSearch = () => {
  customerSearchForm.custCode = ''
  customerSearchForm.custName = ''
  customerSearchForm.custPhone = ''
  customerSearchForm.isEnable = 1
  customerPagination.currentPage = 1

  // 清空选中状态
  selectedCustomer.value = null
  selectedCustomerId.value = ''
  if (customerTableRef.value) {
    customerTableRef.value.setCurrentRow(null)
  }
}

// 客户行点击事件
const handleCustomerRowClick = (row) => {
  selectedCustomer.value = row
  selectedCustomerId.value = row.custId || row.id
  customerTableRef.value?.setCurrentRow(row)
}

// 处理客户单选按钮变化
const handleCustomerRadioChange = (row) => {
  selectedCustomer.value = row
  customerTableRef.value?.setCurrentRow(row)
}

// 确认选择客户
const confirmSelectCustomer = () => {
  if (!selectedCustomer.value) {
    ElMessage.warning('请选择一个客户')
    return
  }

  formData.clientCode = selectedCustomer.value.custCode
  formData.clientName = selectedCustomer.value.custName

  customerDialogVisible.value = false
}

// 初始化
onMounted(() => {
  fetchData()
})

// 获取表格数据
const fetchData = async () => {
  try {
    loading.value = true

    // 构建请求参数
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      workOrderCode: searchParams.workOrderCode || '',
      workOrderName: searchParams.workOrderName || '',
      workOrderSource: searchParams.workOrderSource || '',
      productNumber: searchParams.productNumber || '',
      productName: searchParams.productName || '',
      clientCode: searchParams.clientCode || '',
      clientName: '',
      workOrderType: searchParams.workOrderType || '',
      needsDate: searchParams.needsDate || ''
    }

    // 调用API
    const response = await axios.post('/api/WorkOrder/GetWorkOrder', params)

    console.log(response);


    // 处理响应数据
    if (response.data && response.data.rows) {
      tableData.value = response.data.rows.map(item => ({
        id: item.id || item.workOrderId,
        workOrderCode: item.workOrderCode,
        workOrderName: item.workOrderName,
        workOrderType: item.workOrderType,
        workOrderSource: item.workOrderSource,
        productNumber: item.productNumber,
        productName: item.productName,
        specification: item.specifications || item.specification || '',
        unit: item.unit || '',
        planQuantity: item.workOrderCount || item.planQuantity || 0,
        finishedQuantity: item.finishedQuantity || 0,
        clientCode: item.clientCode || '',
        clientName: item.clientName || '',
        needsDate: item.needsDate ? item.needsDate.split('T')[0] : '',
        status: item.status || 0
      }))
      total.value = response.data.total || 0
    } else if (response.data && response.data.data) {
      // 兼容不同的返回格式
      const rows = response.data.data.rows || []
      tableData.value = rows.map(item => ({
        id: item.id || item.workOrderId,
        workOrderCode: item.workOrderCode,
        workOrderName: item.workOrderName,
        workOrderType: item.workOrderType,
        workOrderSource: item.workOrderSource,
        productNumber: item.productNumber,
        productName: item.productName,
        specification: item.specifications || item.specification || '',
        unit: item.unit || '',
        planQuantity: item.workOrderCount || item.planQuantity || 0,
        finishedQuantity: item.finishedQuantity || 0,
        clientCode: item.clientCode || '',
        clientName: item.clientName || '',
        needsDate: item.needsDate ? item.needsDate.split('T')[0] : '',
        status: item.status || 0
      }))
      total.value = response.data.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取工单数据出错:', error)
    ElMessage.error('获取工单数据出错，请稍后重试')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchParams).forEach(key => {
    searchParams[key] = ''
  })
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchData()
}

// 每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

// 新增
const handleAdd = async () => {
  isEdit.value = false
  dialogVisible.value = true
  autoGenerateCode.value = true
  resetForm()

  // 如果启用了自动生成，则生成工单编号
  if (autoGenerateCode.value) {
    await generateOrderCode()
  }
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  autoGenerateCode.value = false

  // 复制数据到表单
  Object.keys(formData).forEach(key => {
    if (key in row) {
      formData[key] = row[key]
    }
  })
}

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true

    // 调用删除API
    const response = await axios.post(`/api/WorkOrder/DelWorkOrder?ids=${id}`)

    // 处理响应
    if (response) {
      ElMessage.success('删除成功')
      fetchData() // 重新加载数据
    } else {
      const errorMsg = response.data?.msg || '删除失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的工单')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个工单吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true

    // 转换为逗号分隔的字符串
    const ids = selectedIds.value.join(',')

    // 调用批量删除API
    const response = await axios.post(`/api/WorkOrder/DelWorkOrder?ids=${ids}`)

    // 处理响应
    if (response) {
      ElMessage.success('批量删除成功')
      fetchData() // 重新加载数据
    } else {
      const errorMsg = response.data?.msg || '批量删除失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除出错:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.keys(formData).forEach(key => {
    if (key === 'workOrderSource') {
      formData[key] = '客户订单'
    } else if (key === 'workOrderType') {
      formData[key] = '顺序生产'
    } else if (key === 'planQuantity') {
      formData[key] = 1
    } else if (key === 'finishedQuantity') {
      formData[key] = 0
    } else if (key === 'status') {
      formData[key] = 0
    } else {
      formData[key] = ''
    }
  })
}

// 提交表单
const submitForm = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    // 构建请求参数
    const params = {
      id: isEdit.value ? formData.id : 0,
      workOrderCode: formData.workOrderCode,
      workOrderName: formData.workOrderName,
      workOrderType: formData.workOrderType,
      workOrderSource: formData.workOrderSource,
      productNumber: formData.productNumber,
      productName: formData.productName,
      specifications: formData.specification,
      unit: formData.unit,
      workOrderCount: formData.planQuantity,
      needsDate: formData.needsDate,
      remark: formData.remark || '',
      clientCode: formData.clientCode,
      clientName: formData.clientName
    }

    // 根据是否为编辑模式选择不同的API
    const url = isEdit.value ? '/api/WorkOrder/UpdateWorkOrder' : '/api/WorkOrder/CreateWorkOrder'

    // 调用API
    const response = await axios.post(url, params)

    // 处理响应
    if (response) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      fetchData() // 重新加载数据
    } else {
      const errorMsg = response.data?.msg || '操作失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('提交表单出错:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 打开产品选择对话框
const openProductDialog = () => {
  // 重置搜索条件
  resetProductSearch()
  // 加载产品类型树数据
  fetchProductTypeTree()
  // 打开产品选择对话框
  productDialogVisible.value = true
  // 搜索可用产品
  searchProducts()
}

// 确认选择产品
const confirmSelectProduct = () => {
  if (!selectedProduct.value) {
    ElMessage.warning('请选择一个产品')
    return
  }

  formData.productNumber = selectedProduct.value.materialCode
  formData.productName = selectedProduct.value.materialName
  formData.specification = selectedProduct.value.specification
  formData.unit = selectedProduct.value.unit || selectedProduct.value.flats

  productDialogVisible.value = false
}

// 产品分页变化
const handleProductPageChange = (page) => {
  productSearchPagination.currentPage = page
  searchProducts()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr
}

// 获取工单类型文本
const getOrderTypeText = (type) => {
  return type || ''
}

// 获取来源类型文本
const getSourceTypeText = (type) => {
  return type || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已完成',
    2: '已接收'
  }
  return statusMap[status] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'primary'
  }
  return typeMap[status] || 'info'
}

// 处理自动生成开关变化
const handleAutoGenerateChange = async (val) => {
  if (val) {
    // 如果开启自动生成，立即生成编号
    await generateOrderCode()
  } else {
    // 如果关闭自动生成，清空编号
    formData.workOrderCode = ''
  }
}

// 生成工单编号
const generateOrderCode = async () => {
  try {
    // 本地生成编号
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    formData.workOrderCode = `MO${year}${month}${day}${random}`
  } catch (error) {
    console.error('生成工单编号出错:', error)
    // 使用本地生成的编号作为备选
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    formData.workOrderCode = `MO${year}${month}${day}${random}`
  }
}
</script>

<style scoped>
.meading-form-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-container {
  margin-top: 20px;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.total-text {
  margin-right: 15px;
}

.search-input-container {
  display: flex;
  align-items: center;
}

.search-button {
  margin-left: 5px;
}

.product-search {
  margin-bottom: 15px;
}

.product-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 产品选择对话框样式 */
.product-dialog-container {
  display: flex;
  gap: 24px;
  height: 520px;
}

.product-type-tree {
  width: 240px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f9fafc;
  border-radius: 6px;
}

.tree-header {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.tree-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.tree-content {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
}

:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 4px;
  margin-bottom: 2px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f0f2f5;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
}

.product-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.product-search {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
}

/* 美化对话框 */
:deep(.custom-dialog .el-dialog) {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

:deep(.custom-dialog .el-dialog__header) {
  background-color: #f5f7fa;
  padding: 18px 24px !important;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.custom-dialog .el-dialog__title) {
  font-weight: 600;
  font-size: 17px;
  color: #303133;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 28px 24px !important;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

:deep(.custom-dialog .el-dialog__footer) {
  border-top: 1px solid #e4e7ed;
  padding: 16px 24px !important;
}

:deep(.custom-dialog .el-button) {
  border-radius: 4px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.custom-dialog .el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 客户选择对话框样式 */
.customer-dialog {
  /* 添加客户选择对话框的样式代码 */
}

.customer-search {
  /* 添加客户搜索表单的样式代码 */
}

.customer-pagination {
  /* 添加客户分页的样式代码 */
}
</style>
